//
//  WxChannelApi.m
//  kq_flutter_core_widget
//
//  Created by wtb on 2024/12/27.
//

#import "WxChannelApi.h"
#import "WXApi.h"
#import "WechatAuthSDK.h"

static NSString *WX_APPID_KEY = @"wx_appId_key";
static NSString *WX_UNIVERSALLINK_KEY = @"wx_universalLink_key";

static WxChannelApi *wxApi = nil;

@interface WxChannelApi()<WXApiDelegate>

@property(nonatomic,copy) FlutterResult     fResult;
@property(nonatomic,copy) NSString          *appId_record;
@property(nonatomic,copy) NSString          *universalLink_record;

@end

@implementation WxChannelApi

+(instancetype _Nullable)defualtWxChannelApi{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (wxApi == nil) {
            wxApi = [[WxChannelApi alloc] init];
        }
    });
    return wxApi;
}
 
+(BOOL)handleWXOpenURL:(NSURL *)url{
    return [WXApi handleOpenURL:url delegate:[WxChannelApi defualtWxChannelApi]];
}

+(BOOL)handleOpenUniversalLink:(NSUserActivity *)userActivity{
    return [WXApi handleOpenUniversalLink:userActivity delegate:[WxChannelApi defualtWxChannelApi]];
}

-(void)handleWxAuthCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    if (![WXApi isWXAppInstalled]) {
        result(@{@"code":@"2"});
        return;
    }
    if (call.arguments[@"appId"]) {
        NSString *appId = call.arguments[@"appId"];
        NSString *universalLink = call.arguments[@"universalLink"];
        if (self.appId_record != nil && ![self.appId_record isEqualToString:@""] && self.universalLink_record != nil && ![self.universalLink_record isEqualToString:@""]) {
            //存在
            BOOL isNoExit = !([appId isEqualToString:self.appId_record] && [universalLink isEqualToString:self.universalLink_record]);
            if (isNoExit) {
                //传入的数值有变化
                //需要重新注册
                BOOL isSuccess = [WXApi registerApp:appId universalLink:universalLink];
                if (!isSuccess) {
                    //失败 结束
                    return result(@{@"code":@"-1"});
                }
            }
        }else{
            //不存在
            BOOL isSuccess = [WXApi registerApp:appId universalLink:universalLink];
            if (!isSuccess) {
                //失败 结束
                return result(@{@"code":@"-1"});
            }
        }
        self.appId_record = appId;
        self.universalLink_record = universalLink;
    }
    self.fResult = result;
    SendAuthReq *req = [[SendAuthReq alloc] init];
    req.scope = @"snsapi_userinfo";
    req.state = [[NSBundle mainBundle] bundleIdentifier];
    NSNumber *type = call.arguments[@"type"];
    if (type != nil &&[type intValue] == 0) {
        [WXApi sendReq:req
            completion:^(BOOL success){
                // do nothing
            }];
    } else {
        UIViewController *viewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
        [WXApi sendAuthReq:req
            viewController:viewController
                  delegate:self
                completion:^(BOOL success){
                    // do nothing
                }];
    }
}

-(void)handleWxShareTextCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    if (![WXApi isWXAppInstalled]) {
        //没有安装
        result(@(-3));
        return;
    }
    if (call.arguments[@"appId"]) {
        NSString *appId = call.arguments[@"appId"];
        NSString *universalLink = call.arguments[@"universalLink"];
        if (self.appId_record != nil && ![self.appId_record isEqualToString:@""] && self.universalLink_record != nil && ![self.universalLink_record isEqualToString:@""]) {
            //存在
            BOOL isNoExit = !([appId isEqualToString:self.appId_record] && [universalLink isEqualToString:self.universalLink_record]);
            if (isNoExit) {
                //传入的数值有变化
                //需要重新注册
                BOOL isSuccess = [WXApi registerApp:appId universalLink:universalLink];
                if (!isSuccess) {
                    //失败 结束
                    return result(@{@"code":@"-1"});
                }
            }
        }else{
            //不存在
            BOOL isSuccess = [WXApi registerApp:appId universalLink:universalLink];
            if (!isSuccess) {
                //失败 结束
                return result(@{@"code":@"-1"});
            }
        }
        self.appId_record = appId;
        self.universalLink_record = universalLink;
    }
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.scene = WXSceneSession;
    if (call.arguments[@"scene"]) {
        req.scene = [call.arguments[@"scene"] intValue];
    }
    req.bText = YES;
    WXMediaMessage *msg = [[WXMediaMessage alloc] init];
    msg.title = call.arguments[@"title"];
    msg.description = call.arguments[@"desc"];
    FlutterStandardTypedData *typeData = call.arguments[@"icon"];
    msg.thumbData = typeData.data;
//    msg.thumbData = call.arguments[@"icon"];
    req.message = msg;
    [WXApi sendReq:req completion:^(BOOL success) {
        result(success ? @(0) : @(-1));
    }];
}

-(void)handleWxShareWebCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    if (![WXApi isWXAppInstalled]) {
        //没有安装
        result(@(-3));
        return;
    }
    if (call.arguments[@"appId"]) {
        NSString *appId = call.arguments[@"appId"];
        NSString *universalLink = call.arguments[@"universalLink"];
        if (self.appId_record != nil && ![self.appId_record isEqualToString:@""] && self.universalLink_record != nil && ![self.universalLink_record isEqualToString:@""]) {
            //存在
            BOOL isNoExit = !([appId isEqualToString:self.appId_record] && [universalLink isEqualToString:self.universalLink_record]);
            if (isNoExit) {
                //传入的数值有变化
                //需要重新注册
                BOOL isSuccess = [WXApi registerApp:appId universalLink:universalLink];
                if (!isSuccess) {
                    //失败 结束
                    return result(@{@"code":@"-1"});
                }
            }
        }else{
            //不存在
            BOOL isSuccess = [WXApi registerApp:appId universalLink:universalLink];
            if (!isSuccess) {
                //失败 结束
                return result(@{@"code":@"-1"});
            }
        }
        self.appId_record = appId;
        self.universalLink_record = universalLink;
    }
    if (call.arguments[@"url"]) {
        WXWebpageObject *mediaObject = [WXWebpageObject object];
        mediaObject.webpageUrl = call.arguments[@"url"];
        SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
        req.scene = WXSceneSession;
        if (call.arguments[@"scene"]) {
            req.scene = [call.arguments[@"scene"] intValue];
        }
        req.bText = NO;
        WXMediaMessage *msg = [[WXMediaMessage alloc] init];
        msg.title = call.arguments[@"title"];
        msg.description = call.arguments[@"desc"];
        FlutterStandardTypedData *typeData = call.arguments[@"icon"];
        msg.thumbData = typeData.data;
//        msg.thumbData = call.arguments[@"icon"];
        msg.mediaObject = mediaObject;
        req.message = msg;
        [WXApi sendReq:req completion:^(BOOL success) {
            result(success ? @(0) : @(-1));
        }];
    }else{
        result(@(-1));
    }
}

-(void)handleWxShareImageCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    if (![WXApi isWXAppInstalled]) {
        //没有安装
        result(@(-3));
        return;
    }
    if (call.arguments[@"appId"]) {
        NSString *appId = call.arguments[@"appId"];
        NSString *universalLink = call.arguments[@"universalLink"];
        if (self.appId_record != nil && ![self.appId_record isEqualToString:@""] && self.universalLink_record != nil && ![self.universalLink_record isEqualToString:@""]) {
            //存在
            BOOL isNoExit = !([appId isEqualToString:self.appId_record] && [universalLink isEqualToString:self.universalLink_record]);
            if (isNoExit) {
                //传入的数值有变化
                //需要重新注册
                BOOL isSuccess = [WXApi registerApp:appId universalLink:universalLink];
                if (!isSuccess) {
                    //失败 结束
                    return result(@{@"code":@"-1"});
                }
            }
        }else{
            //不存在
            BOOL isSuccess = [WXApi registerApp:appId universalLink:universalLink];
            if (!isSuccess) {
                //失败 结束
                return result(@{@"code":@"-1"});
            }
        }
        self.appId_record = appId;
        self.universalLink_record = universalLink;
    }
    WXImageObject *mediaObject = [WXImageObject object];
    FlutterStandardTypedData *imageData = call.arguments[@"bytes"];
    if (imageData != nil) {
        mediaObject.imageData = imageData.data;
    } else {
        NSString *imageUri = call.arguments[@"localPath"];
        NSURL *imageUrl = [NSURL URLWithString:imageUri];
        mediaObject.imageData = [NSData dataWithContentsOfFile:imageUrl.path];
    }
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.scene = WXSceneSession;
    if (call.arguments[@"scene"]) {
        req.scene = [call.arguments[@"scene"] intValue];
    }
    req.bText = NO;
    WXMediaMessage *msg = [[WXMediaMessage alloc] init];
    msg.title = call.arguments[@"title"];
//        msg.description = call.arguments[@"desc"];
//        FlutterStandardTypedData *typeData = call.arguments[@"icon"];
//        msg.thumbData = typeData.data;
//        msg.thumbData = call.arguments[@"icon"];
    msg.mediaObject = mediaObject;
    req.message = msg;
    [WXApi sendReq:req completion:^(BOOL success) {
        result(success ? @(0) : @(-1));
    }];
}

-(void)openMiniProgramCall:(FlutterMethodCall *)call result:(FlutterResult)result{
    self.fResult = result;
    WXLaunchMiniProgramReq *req = [[WXLaunchMiniProgramReq alloc] init];
    req.userName = call.arguments[@"username"];
    req.path = call.arguments[@"path"];
    if(call.arguments[@"type"]){
        NSNumber *miniProgramType = call.arguments[@"type"];
        req.miniProgramType = miniProgramType.unsignedIntegerValue;
    }else{
        req.miniProgramType = WXMiniProgramTypeRelease;
    }
    [WXApi sendReq:req
        completion:^(BOOL success){
            // do nothing
        }];
}

- (void)onResp:(BaseResp *)resp {
    if (resp.errStr != nil) {
        if (self.fResult != nil) {
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setValue:@"0" forKey:@"code"];
            [dic setValue:resp.errStr forKey:@"msg"];
            [dic setValue:[NSString stringWithFormat:@"%d",resp.errCode] forKey:@"data"];
            self.fResult(dic);
            return;
        }
    }
    
    if (self.fResult != nil) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        if ([resp isKindOfClass:[SendAuthResp class]]) {
            SendAuthResp *authResp = (SendAuthResp *)resp;
            if (authResp.errCode == WXSuccess) {
                [dic setValue:@"0" forKey:@"code"];
                [dic setValue:authResp.code forKey:@"authCode"];
                [dic setValue:authResp.state forKey:@"state"];
                [dic setValue:authResp.lang forKey:@"lang"];
                [dic setValue:authResp.country forKey:@"country"];
            }else if (authResp.errCode == WXErrCodeUserCancel){
                [dic setValue:@"-1" forKey:@"code"];
                [dic setValue:@"用户点击取消并返回" forKey:@"msg"];
            }else{
                [dic setValue:@"1" forKey:@"code"];
                [dic setValue:@"微信授权登录失败" forKey:@"msg"];
            }
            self.fResult(dic);
        }else if ([resp isKindOfClass:[SendMessageToWXResp class]]){
            SendMessageToWXResp *sendResp = (SendMessageToWXResp *)resp;
            if (sendResp.errCode == WXSuccess) {
                [dic setValue:@"1" forKey:@"code"];
                [dic setValue:sendResp.lang forKey:@"lang"];
                [dic setValue:sendResp.country forKey:@"country"];
            }else if (sendResp.errCode == WXErrCodeUserCancel){
                [dic setValue:@"-1" forKey:@"code"];
                [dic setValue:@"用户点击取消并返回" forKey:@"msg"];
            }else{
                [dic setValue:@"0" forKey:@"code"];
                [dic setValue:@"微信分享失败" forKey:@"msg"];
            }
            self.fResult(dic);
        }else if ([resp isKindOfClass:[LaunchFromWXReq class]]){
            if (resp.errCode == WXSuccess) {
                [dic setValue:@"1" forKey:@"code"];
            }else{
                [dic setValue:@"0" forKey:@"code"];
            }
            self.fResult(dic);
        }
    }
    
}


@end
